package com.fingersoft.feature.cordova

import android.Manifest
import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import cn.fingersoft.facebook.react.bridge.runOnUiThread
import cn.fingersoft.jsapi.plugin.api.ApiJSApiPlugin
import cn.fingersoft.jsapi.plugin.im.ChatJSApiPlugin
import cn.fingersoft.jsapi.plugin.watermarkview.WatermarkJSApiPlugin
import cn.fingersoft.util.BuildConfigUtil
import com.cordova.plugin.CordovaBehaviorListener
import com.cordova.plugin.CordovaPluginContext
import com.cordova.signpad.SignPadJSApiPlugin
import com.fingersoft.android.app.PermissionUtils
import com.fingersoft.business.BusinessContext
import com.fingersoft.business.jsapi.JsapiManager
import com.fingersoft.business.webview.IWebViewProvider
import com.fingersoft.cordova.CordovaContext
import com.fingersoft.cordova.ICordovaContext
import com.fingersoft.feature.faceId.FaceIDExport
import com.fingersoft.feature.newlock.LockContext
import com.fingersoft.feature.newlock.LockManager
import com.fingersoft.feature.webview.CordovaWebViewActivity
import com.fingersoft.feature.webview.WebViewManager
import com.fingersoft.feature.webview.webapp.WebAppManager
import com.fingersoft.im.utils.*
import com.fingersoft.im.webview.CommonWebViewActivity
import com.fingersoft.plugins.scancode.zxing.activity.CaptureActivity
import com.fingersoft.plugins.scancode.zxing.activity.CustomCaptureActivity
import com.fingersoft.plugins.video.VideoJSApi
import com.fingersoft.remotefile.IRemotefileJSApiPlugin
import com.fingersoft.util.AppEventUtil
import org.apache.cordova.CallbackContext
import org.apache.cordova.CordovaPlugin
import org.apache.cordova.PluginResult
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject

open class SealCordovaContext : ICordovaContext {
    override fun getUid(): String? {
        return AppUtils.getTokenInfo().uid
    }

    override fun getDeviceId(): String? {
        return AppUtils.getTokenInfo().did
    }
    override fun registerPlugins(activity: Activity,jsapiManager: JsapiManager):JsapiManager{
        //todo 重构 jsapi的注册到各个独立的模块的插件中
        jsapiManager
            .register("www/library/emp-signpad.js", SignPadJSApiPlugin::class.java)
            .register("www/library/emp-chat.js", ChatJSApiPlugin::class.java)
            .register("www/library/emp-remotefile.js", IRemotefileJSApiPlugin::class.java)
            .register("www/library/emp-watermark.js", WatermarkJSApiPlugin::class.java)
            .register("www/library/emp-video.js", VideoJSApi::class.java)
            .addPluginHandler(ApiJSApiPlugin::class.java)

        if (AppUtils.useFaceID()) {
            FaceIDExport.getJSApiPluginClass()?.let {
                jsapiManager.register("www/library/emp-faceID.js", it)
            }
        }
        return jsapiManager
    }

    override fun webviewRotateEnable(): Boolean {
        return AppUtils.webviewRotateEnable()
    }

    override fun useRong(): Boolean {
        return AppUtils.useRong()
    }

    override fun getApiUrl(s: String): String? {
        return AppUtils.getApiUrl(s)
    }

    override fun get_collect(): List<AllCollectParam> {
        return BusinessContext.collect?.getCollect() ?: ArrayList()
    }

    override fun saveh5state(stype: Int, apptype: String?, appid: String?, appVersion: String?) {
        AppEventUtil.writeLandingState(stype,apptype,appid,appVersion)
    }


    override fun isCordovaDebuggable(): Boolean {
        return PreferenceHelper.getBoolean("CORDOVA_DEBUGGABLE", false)
    }

    companion object {

        fun init(application: Application) {
            BusinessContext.webViev = object : IWebViewProvider {
                override fun openAppWebView(context: Context, url: String, title: String?, type: String?, appId: String, appVersion: String?) {
                    WebAppManager.start(context, url, title, type, appId, appVersion)
                }

                override fun startCordovaWebViewActivity(context: Context, url: String?, title: String?) {
                    CordovaWebViewActivity.startActivity(context, url, title)
                }

                override fun openAndSearch(context: Context?, url: String?) {
                    context?.runOnUiThread {
                        openApp(context, url, null, "voiceassistant")
                    }
                }

                override fun openWebView(activity: Context, url: String?, title: String?) {
                    WebViewManager.openWebView(activity, url, title)
                }

                override fun openApp(context: Context?, url: String?, title: String?, from: String?) {

                    context?.let {
                        if ("notification" == from) {
                            val intent = Intent(context, CordovaWebViewActivity::class.java)
                            intent.putExtra("activity", CordovaWebViewActivity::class.java)
                            intent.putExtra("url", url)
                            intent.putExtra("title", title)
                            from.let { intent.putExtra("from", from) }
                            if (context !is Activity) {
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                            }
                            startActivityWithAppIsRunning(context, intent)
                        } else {
                            WebAppManager.start(it, url ?: "", title ?: "", from)
                        }
                    }
                }

                override fun openCommonWebView(activity: Context, url: String?, title: String?, fullscreen: Boolean) {
                    CommonWebViewActivity.start(activity, url, title, false)
                }
            }
            CordovaPluginContext.init(application)
            CordovaPluginContext.getInstance().cordovaBehaviorListener = object : CordovaBehaviorListener {
                override fun onScanReader(cordovaPlugin: CordovaPlugin, action: String, args: JSONArray, callbackContext: CallbackContext): Boolean {
                    val cordova = cordovaPlugin.cordova
                    if (!PermissionUtils.getInstance(cordova.context).checkPermission(Manifest.permission.CAMERA, null)) {
                        ToastUtils.show("您没有开启摄像头权限")
                        return false
                    }
                    try {
                        val needResult = getNeedResult(args)
                        if (TextUtils.isEmpty(needResult) || needResult == "0") {
                            CustomCaptureActivity.start(cordova.activity)
                            callbackContext.success()
                        } else {
                            val intent = Intent(cordova.activity, CustomCaptureActivity::class.java)
                            cordova.startActivityForResult(cordovaPlugin, intent, CaptureActivity.RESULT_CODE_QR_SCAN)
                            val result = PluginResult(PluginResult.Status.NO_RESULT)
                            result.keepCallback = true
                            callbackContext.sendPluginResult(result)
                        }
                        return true
                    } catch (e: JSONException) {
                        e.printStackTrace()
                        callbackContext.error(e.message)
                    }

                    return false
                }

                @Throws(JSONException::class)
                private fun getNeedResult(args: JSONArray): String? {
                    val json = args.getString(0)
                    if (TextUtils.isEmpty(json) || "null" == json) {
                        return null
                    }
                    val jsonObject = JSONObject(json)
                    return jsonObject.getString("needResult")
                }

                override fun onQuanshiStart(plugin: CordovaPlugin, meetingId: String): Boolean {
                    return false
                }

                override fun onGesturePasswordShow(instanceId: String) {
                    //目前只有jsapi调用
                    LockContext.instance.onModuleCreate(application.applicationContext)
                    LockManager.instance.doUnLock(LockManager.LOCK_TYPE_AUTO, BuildConfigUtil.getBoolean("lock_jsapi_back_to_exit", false), instanceId)
                }

                override fun onGesturePasswordShow() {
                    onGesturePasswordShow("")
                }

                override fun onStartPrivateChat(activity: Activity, id: String, title: String) {
                    BusinessContext.im?.startPrivateChatByImid(activity, id, title);
                }
            }
            CordovaContext.init(SealCordovaContext())
        }
    }
}
